import router from '@/router'
import axios, { type AxiosPromise } from 'axios'
import { ElMessageBox } from 'element-plus'

class HttpRequest {
  constructor() {
    // axios.defaults.baseURL = "http://localhost:8089"
    axios.defaults.baseURL = "http://47.103.9.159:8089"
    // 添加请求拦截器
    axios.interceptors.request.use(
      (config) => {
        //请求拦截器统一在头部添加token
        config.headers.set('token', window.localStorage.getItem('dlyk_login_token'))
        return config
      },
      (err) => {
        return Promise.reject(err)
      },
    )
    // 添加响应拦截器
    axios.interceptors.response.use(
      (response) => {
        // 2xx 范围内的状态码都会触发该函数。
        // 对响应数据做点什么
        if (response.data.code == 901 || response.data.code == 902 || response.data.code == 903) {
          window.localStorage.removeItem('dlyk_login_token')
          window.localStorage.removeItem('buttonPermission')
          ElMessageBox.confirm('登录已失效', 'Warning', {
            confirmButtonText: '去登录',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              router.replace({
                path: '/login',
              })
            })
            .catch(() => {})
        }
        return response
      },
      (error) => {
        // 超出 2xx 范围的状态码都会触发该函数。
        // 对响应错误做点什么
        return Promise.reject(error)
      },
    )
  }

  public doGet(url: string, param: any): AxiosPromise {
    return axios({
      method: 'get',
      url: url,
      params: param,
    })
  }

  public doPost(url: string, data: any): AxiosPromise {
    return axios({
      method: 'post',
      url: url,
      data: data,
    })
  }

  public doPut(url: string, data: any): AxiosPromise {
    return axios({
      method: 'put',
      url: url,
      data: data,
    })
  }

  public doDelete(url: string, param: any): AxiosPromise {
    return axios({
      method: 'delete',
      url: url,
      params: param,
    })
  }
}

export default new HttpRequest()
